<template>
    <el-container class="container" >
      <div class="header">
        <Header @submit="handleSubmitFather"  />
      </div>
      <div class="middle">
        <div class="aside">              
            <ChapterSectionMenu v-if="state.showMenu" :menu_list="state.chapterSectionMenu" @submit="handleSelectKnowledgepointSubmitFather" />         
            <PaperMenu v-if="state.showPaperMenu" :menu_list="state.paperMenu"/>
            <GenaralPaperMenu v-if="state.showGenaralPaperMenu" :menu_list="state.genaralPaperMenu"/>
            <KnowledgePointMenu v-if="state.showKnowledgepointMenu" :categoryData="state.knowledgepointMenu" />
            <UserCenterMenu v-if="state.showUserCenterMenu" />
            <AdminMenu v-if="state.showAdminMenu" />
            <GuidePaperMenu v-if="state.showGuidePaperMenu" />
            <ChapterSectionMenuPrivate v-if="state.showMenuPrivate" />
            <!-- <KnowledgePointMenu v-if="state.showKnowledgepointMenu" :categoryData="state.knowledgepointMenu" /> -->
        </div>
        <div class="main">
          <router-view />
        </div> 
      </div>
      <Footer />
    </el-container>
</template>
<script setup>
import { onMounted, reactive } from "@vue/runtime-core"
import Header from '@/components/Header.vue';
import Footer from '@/components/Footer.vue';
import PaperMenu from '@/components/PaperMenu.vue';
import GenaralPaperMenu from '@/components/GenaralPaperMenu.vue';
import ChapterSectionMenu from '@/components/ChapterSectionMenu.vue';
import ChapterSectionMenuPrivate from '@/components/ChapterSectionMenuPrivate.vue';
import KnowledgePointMenu from '@/components/KnowledgePointMenu.vue';
import AdminMenu from '@/components/AdminMenu.vue';
import UserCenterMenu from '@/components/UserCenterMenu.vue';
import GuidePaperMenu from '@/components/GuidePaperMenu.vue';
import { useRoute, useRouter } from "vue-router";
import { localGet, localSet,  pathMap, deepClone } from '@/utils'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'

const store=useStore()
const chapterSectionMenuPrivateList = ['/showQuestionPrivate', ]
const guidePaperList = ['/getGuidePapersByKnowledgepoint']
const chapterSectionMenuList = ['/getQuestionsByCourse', '/getQuestionsByChapter', '/getQuestionsBySection', '/getQuestionsByKnowledgepoint']
const paperMenuList = ['/getQuestionsByPaper', '/getPaper']
const genaralPaperMenuList = ['/getQuestionsByGenaralPaper']
const knowledgepointMenuList = ['/addPaperByFileStepTwo']
const userCenterMenuList = ['/userCenter', '/userCenter/userInformation', '/userCenter/changePassword', '/userCenter/MyNotification',
      '/userCenter/myFavoriteQuestions','/userCenter/myCreatePaper','/userCenter/myCreateQuestion', '/userCenter/myCreateQuestionAll',
      '/userCenter/myCreateGuidePaper', '/userCenter/myBankPoint','/userCenter/withdraw','/userCenter/recharge','/userCenter/addNode',
      '/userCenter/myPrivateQuestion',
      ]
const adminMenuList = [
  '/adminCenter', '/adminCenter/activateAccountManage', '/adminCenter/VIPManage', '/adminCenter/nicknameManage', 
  '/adminCenter/jointPaperQuestionManage','/adminCenter/generalPaperQuestionManage','/adminCenter/notPaperQuestionManage',
  '/adminCenter/jointPaperManage','/adminCenter/generalPaperManage','/adminCenter/notPaperManage','/adminCenter/guidePaperManage',
  '/adminCenter/generalFeekbackManage','/adminCenter/questionFeedbackManage','/adminCenter/guidePaperFeedbackManage',
  '/adminCenter/feedbackManage','/adminCenter/withdrawLogManage','/adminCenter/rechargeLogManage', '/adminCenter/questionPrivateManage',
]
const router =useRouter()
const route =useRoute()
const state = reactive({
     //是否需要显示左侧的章节目录
    showGuidePaperMenu: false,
    showMenu: false,
    showPaperMenu: false,
    showMenuPrivate: false,
    showGenaralPaperMenu: false,
    showKnowledgepointMenu: false,
    showUserCenterMenu: false,
    showAdminMenu: false,
    loading: false,
    paperMenu: [],            //联考试卷
    genaralPaperMenu:[],    //非联考一般试卷
    chapterSectionMenu: [],   // 侧边章节
    knowledgepointMenu: [],   // 侧边知识点
    total:0,
    currentPage:1,
    pageSize:10,
    select_knowledge_id: 0, 
    clearList:[],
})
onMounted(()=>{
    getCategory()
    getPaperCategory()
    getGenarelPaperCategory()
    // getKnowledgePointCategory()    
})

// 获取课程
const getCategory=()=>{
  const chapterSectionMenuCache = localGet('chapterSectionMenuCache')
  const chapterSectionMenuCacheStartTime = localGet('chapterSectionMenuStartTime')
  // console.log('chapterSectionMenuCache:', chapterSectionMenuCache)
  // console.log('chapterSectionMenuStartTime:', chapterSectionMenuStartTime)
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
  if(chapterSectionMenuCache !=undefined && chapterSectionMenuCacheStartTime!=undefined && chapterSectionMenuCacheStartTime>20240000){ 
    const dateDiff = currentTime - chapterSectionMenuCacheStartTime // 获取两个时间的差值（以秒为单位）
    if(dateDiff <= 1){    
        console.log('从缓存恢复课程：',chapterSectionMenuCache)
        state.chapterSectionMenu = chapterSectionMenuCache
        return 1    
    }
  }
  axios.get('/courses').then(res => {
    console.log('后台获取所有课程：', res)
      if (res.code==200){
          state.chapterSectionMenu = res.data.results
          localSet('chapterSectionMenuCache', res.data.results)
          localSet('chapterSectionMenuStartTime', currentTime)
          // console.log('存入缓存chapterSectionMenuStartTime', localGet('chapterSectionMenuStartTime'))
      }else{
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取章节菜单错误：", error)
  })
}
// 获取知识点目录
const getKnowledgePointCategory=()=>{
  const knowledgePointCache = localGet('knowledgePointCache')
  const knowledgePointStartTime = localGet('knowledgePointStartTime')
  console.log('knowledgePointStartTime:', knowledgePointStartTime)
  console.log('knowledgePointCache:', knowledgePointCache)
  const currentDate = new Date();
  if(knowledgePointCache!=undefined && knowledgePointStartTime!=undefined){
    if(typeof knowledgePointStartTime==='object' && Object.keys(knowledgePointStartTime)>0){    
      const dateDiff = currentDate.getDate() - knowledgePointStartTime
      if(dateDiff <=1){
        if(knowledgePointCache!=[]){
          state.knowledgepointMenu = knowledgePointCache
          return 1
        }
      }
    }
  }
  
  let params = {size:100}
  axios.get('/knowledgepoints',{params}).then(res => {  
    console.log('后台获取知识点目录：',res)
      if (res.code==200){
          state.knowledgepointMenu = res.data.results
          localSet('knowledgePointCache', res.data.results)
          localSet('knowledgePointStartTime', currentDate.getDate())
          console.log('放入缓存后的知识点time：', localGet('knowledgePointStartTime'))
      }else{       
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取知识点错误：", error)
  })
}
// 获取联考试卷目录
const getPaperCategory=()=>{
  const paperMenuCache = localGet('paperMenuCache')
  const paperMenuCacheStartTime = localGet('paperMenuCacheStartTime')
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
  if(paperMenuCache !=undefined && paperMenuCacheStartTime!=undefined && paperMenuCacheStartTime>20240000){
    const dateDiff = currentTime - paperMenuCacheStartTime
    if(dateDiff <= 1){
      if(state.paperMenu==[]){
        state.paperMenu = paperMenuCache
        return 1
      }
    }
  }
  let params = { is_joint: 1 }
  axios.get(`/GetPaperMenuByDateAndGrade/`, {params}).then(res => {
      if (res.code==200){
        console.log('后台获取联考卷目录：', res.data.results)
        state.paperMenu = res.data.results
        localSet('paperMenuCache', res.data.results)
        localSet('paperMenuCacheStartTime', currentTime)
      }else{
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取试卷目录错误：", error)
  })
}
// 获取非联考试卷目录
const getGenarelPaperCategory=()=>{
  const genaralPaperMenuCache = localGet('genaralPaperMenuCache')
  const genaralPaperMenuCacheStartTime = localGet('genaralPaperMenuCacheStartTime')
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
  if(genaralPaperMenuCache!=undefined && genaralPaperMenuCacheStartTime!=undefined && genaralPaperMenuCacheStartTime>20240000){
    const dateDiff = currentTime - genaralPaperMenuCacheStartTime
    if(dateDiff <= 1){
      if(state.genaralPaperMenu==[]){
        state.genaralPaperMenu = genaralPaperMenuCache
        return 1
      }  
    }
  }
    let params = { is_joint: 0 }
    axios.get(`/GetPaperMenuByDateAndGrade/`, {params}).then(res => {
        if (res.code==200){
          console.log('后台获取非联考卷目录：', res.data.results)
          state.genaralPaperMenu = res.data.results
          localSet('genaralPaperMenuCache', res.data.results)
          localSet('genaralPaperMenuCacheStartTime', currentTime)
        }else{       
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取试卷目录错误：", error)
    })
}

// 路由监测,写到route/index.js中去了
router.beforeEach((to, from, next)=>{
  console.log('beforeach的to',to)
  if(!(to.name=='signin' || to.name=='resetPassword' || to.name=='chatCompletion' || to.name=='index'|| to.name=='tex2pdf' || to.name=='handingWriteOCR')){
      verifyToken()
    }
  if(to.path!='/signin'&&to.path!='/login'){
    state.showMenuPrivate = chapterSectionMenuPrivateList.includes(to.path)
    state.showMenu = chapterSectionMenuList.includes(to.path)
    state.showPaperMenu = paperMenuList.includes(to.path)
    state.showGenaralPaperMenu = genaralPaperMenuList.includes(to.path)
    state.showKnowledgepointMenu = knowledgepointMenuList.includes(to.path)
    state.showUserCenterMenu = userCenterMenuList.includes(to.path)
    state.showAdminMenu = adminMenuList.includes(to.path)
    state.showGuidePaperMenu = guidePaperList.includes(to.path)
    // getKnowledgePointCategory()
  }
    next()
})
// 检验token是否有效
const verifyToken = ()=> {
  axios.get('/VerifyToken/').then(res => {
    // console.log('根据令牌', res)
        if (res.code==200){
            localSet('user_information', res.data.results)
            localSet('isLogin', true)
            return true
        }else if(res.code==403){
            ElMessage.warning("你的令牌已过期，请重新登录!")
            router.push('/login')
        }else{
          ElMessage.warning("系统错误，请联系管理员!")
        }
    })
    .catch((error)=>{
        console.log("verifyToken", error)
        ElMessage.warning("你的令牌已过期，请重新登录获取!")
        router.push('/login')
    })
}

const handleSubmitFather=(menu)=>{
  console.log("执行子组件的回调函数")
}
const handleSelectKnowledgepointSubmitFather=(knowledgepoint_id)=>{
  console.log("执行子组件章节菜单点击的回调函数")
  state.select_knowledge_id = knowledgepoint_id
}
</script>


<style scoped>
.header{
  /* z-index: 0; */
  margin: 0;
  padding: 0;
}
.middle{
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-content: flex-start;
  min-height: 100vh;
  overflow: hidden;
  margin: 1px 0 0 0;
  /* z-index:2; */
}
.container {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  /* min-height: 100vh; */
  background-color: #ffffff;
  /* height: 100vh; */
}
.aside {
  width: 230px!important;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main {
  display: block;

  margin: 10px 0 0 0;
  padding: 1px;
  /* z-index:2; */
}
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
a{
  text-decoration: none;
  color: #000;
}
</style>